﻿using FineAdmin.IService;
using FineAdmin.Web.CommonService;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace FineAdmin.Web.JobWork
{
    public class HuiJiWork
    {

        public async static Task Run()
        {
            var properties = new NameValueCollection();
            // 设置线程池
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            //设置线程池的最大线程数量
            properties["quartz.threadPool.threadCount"] = "5";
            //设置作业中每个线程的优先级
            properties["quartz.threadPool.threadPriority"] = ThreadPriority.Normal.ToString();
            // 远程输出配置
            properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
            properties["quartz.scheduler.exporter.port"] = "1996";  //配置端口号
            properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
            properties["quartz.scheduler.exporter.channelType"] = "tcp"; //协议类型

            // 1.创建scheduler的引用
            //创建一个工厂
            //var schedulerFactory = new StdSchedulerFactory(properties);
            ISchedulerFactory schedFact = new StdSchedulerFactory(properties);

            //2.启动 scheduler
            //启动
            //var scheduler = schedulerFactory.GetScheduler();
            IScheduler sched = await schedFact.GetScheduler();

            await sched.Start();


            // 3.创建 job 

            IJobDetail job = JobBuilder.Create<SimpleJob>()
                    .WithIdentity("job1", "group1") //
                    .Build();

            IJobDetail Ldjob = JobBuilder.Create<LingDianJob>()
                   .WithIdentity("ldjob1", "group1") //
                   .Build();

            IJobDetail rushjob = JobBuilder.Create<RushJob>()
                  .WithIdentity("rushjob", "group1") //
                  .Build();

            // 4.创建 trigger 触发器 

            //每30分钟执行一次
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(60*30).RepeatForever())
                .Build();

            //每天凌晨1点执行
            ITrigger trigger0 = TriggerBuilder.Create()
               .WithCronSchedule("0 0 1 * * ?").Build();

            ITrigger trigger1 = TriggerBuilder.Create()
               .WithIdentity("rushtrigger", "group1")
                .WithSimpleSchedule(x => x.WithIntervalInHours(2).RepeatForever())
                .Build();

            // 5.使用trigger规划执行任务job
            await sched.ScheduleJob(job, trigger);
            await sched.ScheduleJob(Ldjob, trigger0);
            await sched.ScheduleJob(rushjob, trigger1);
        }

        /// <summary>
        /// 任务 更新 商品数据 删除超期数据 
        /// </summary>
        public class SimpleJob : IJob
        {
            //通过服务容器获取
            private readonly IMaterialService MaterialService = ServiceLocator.GetService<IMaterialService>();
            private readonly IMaterialGoodsService MaterialGoodsService = ServiceLocator.GetService<IMaterialGoodsService>();
            private readonly ISystemParameterService SystemParameterService = ServiceLocator.GetService<ISystemParameterService>();
            //public IMaterialService MaterialService { get; set; }
            public virtual Task Execute(IJobExecutionContext context)
            {
                //var reportDirectory = string.Format("~/text/{0}/", DateTime.Now.ToString("yyyy-MM-dd-ssss"));
                //reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory);
                //if (!Directory.Exists(reportDirectory))
                //{
                //    Directory.CreateDirectory(reportDirectory);
                //}
                //var dailyReportFullPath = string.Format("{0}text_{1}.log", reportDirectory, DateTime.Now.Day);
                //var logContent = string.Format("{0}-{1}-{2}", DateTime.Now, "滴 滴滴", Environment.NewLine);
                //if (logContent == null)
                //{
                //    JobExecutionException jobex = new JobExecutionException("写入失败");

                //}
                //File.AppendAllText(dailyReportFullPath, logContent);


                //更新数据
                var b=SystemParameterService.GetByCode("EnableAutoUupdateTBK").SPValue=="1";
                if (b)
                {
                    Log.WriteInfo("开始进行商品数据更新（全量）");
                    var ret = MaterialService.RefreshData(-1, true);
                    //删除超期数据
                    var ret2 = MaterialGoodsService.OverData();
                }
                return null;
            }

        }

        public class LingDianJob : IJob
        {
            //通过服务容器获取
            private readonly IMaterialService MaterialService = ServiceLocator.GetService<IMaterialService>();
            private readonly IRushService RushService = ServiceLocator.GetService<IRushService>();
            private readonly ISystemParameterService SystemParameterService = ServiceLocator.GetService<ISystemParameterService>();
            //public IMaterialService MaterialService { get; set; }
            public virtual Task Execute(IJobExecutionContext context)
            {
                //var reportDirectory = string.Format("~/text/{0}/", DateTime.Now.ToString("yyyy-MM-dd-ssss"));
                //reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory);
                //if (!Directory.Exists(reportDirectory))
                //{
                //    Directory.CreateDirectory(reportDirectory);
                //}
                //var dailyReportFullPath = string.Format("{0}text_{1}.log", reportDirectory, DateTime.Now.Day);
                //var logContent = string.Format("{0}-{1}-{2}", DateTime.Now, "滴 滴滴", Environment.NewLine);
                //if (logContent == null)
                //{
                //    JobExecutionException jobex = new JobExecutionException("写入失败");

                //}
                //File.AppendAllText(dailyReportFullPath, logContent);

                //更新数据
                var b = SystemParameterService.GetByCode("EnableAutoUupdateTBK").SPValue == "1";
                if (b)
                {
                    var ret = MaterialService.RefreshData(-1, true, true);
                    var ret2 = RushService.CreateData();
                }
                return null;
            }
        }

        public class RushJob : IJob
        {
            private readonly IRushService RushService = ServiceLocator.GetService<IRushService>();
            public virtual Task Execute(IJobExecutionContext context)
            {
                var ret = RushService.CreateData();
                return null;
            }
        }
    }
}